package org.grapes.wine.api.client.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Visitor;
import org.dom4j.VisitorSupport;
import org.dom4j.XPath;

@Deprecated
public class WineMethodDataAnaylsis {
	/*
	 * The data of Document is XML format
	 */
	public static List<Map> documentToList(Document doc) {
		// inner class for XPath visitor
		class Visitor extends VisitorSupport {
			final private Map map = new HashMap();

			public Map getMap() {
				return map;
			}

			public void visit(Element node) {
				// except data node, other's node must not contain text
				if (node.getText().length() != 0) {
					map.put(node.getName(), node.getText());
				}
			}
		}
		;

		List<Map> dataList = new ArrayList<Map>();

		// error XPath
		String expr = "//error";
		XPath XPath = DocumentHelper.createXPath(expr);
		List data = XPath.selectNodes(doc);
		
		Iterator it2 = data.iterator();
		if (it2.hasNext()) {
			Visitor visitor = new Visitor();
			Element element = (Element) it2.next();
			element.accept(visitor);
			dataList.add(visitor.getMap());
		}
		
		// normal XPath
		if (data.size() == 0) {
			// data id is start from 1
			expr = "//data[@id = '1']";
			XPath = DocumentHelper.createXPath(expr);
			data = XPath.selectNodes(doc);
			int i = 2;
			// Guarantee that XPath.selectNodes(doc) is not empty
			while (data.size() != 0) {
				Iterator it = data.iterator();
				if (it.hasNext()) {
					Visitor visitor = new Visitor();
					Element element = (Element) it.next();
					element.accept(visitor);
					dataList.add(visitor.getMap());
				}

				expr = "//data[@id ='" + i + "']";
				XPath = DocumentHelper.createXPath(expr);
				data = XPath.selectNodes(doc);
				i++;
			}			
		}
		return dataList;
	}
}
